package com.example.xxpk.service.userenergys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.xxpk.mapper.UserEnergysMapper;
import com.example.xxpk.pojo.UserEnergys;
import com.example.xxpk.pojo.Users;
import com.example.xxpk.service.users.IUsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangguihong
 * @since 2025-02-22
 */
@Service
@RequiredArgsConstructor
public class UserEnergysServiceImpl extends ServiceImpl<UserEnergysMapper, UserEnergys> implements IUserEnergysService {

    private final IUsersService usersService;

    @Override
    public UserEnergys addEnergys(Integer userId, Integer type) {
        LambdaQueryWrapper<UserEnergys> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEnergys::getUserId,userId)
                    .eq(UserEnergys::getType,type);
        UserEnergys userEnergys = this.getOne(queryWrapper);
        if (userEnergys !=null) {
            Integer count = userEnergys.getCount();
            if (type == 1) {
                if (count >= 3) {
                    throw new RuntimeException("今日分享已达上线");
                }
                Users user = usersService.getById(userId);
                user.setEnergys(user.getEnergys() + 5);
                usersService.updateById(user);
            } else {
                if (count >= 5) {
                    throw new RuntimeException("今日观看广告已达上线");
                }
                Users user = usersService.getById(userId);
                user.setEnergys(user.getEnergys() + 15);
                usersService.updateById(user);
            }
            userEnergys.setCount(userEnergys.getCount()+1);
            this.saveOrUpdate(userEnergys);
        }
        else {
            userEnergys = new UserEnergys();
            userEnergys.setUserId(userId);
            userEnergys.setType(type);
            userEnergys.setCount(1);
            this.save(userEnergys);
        }

        return userEnergys;
    }
}
